// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2004-11-20

#include "stdafx.h"
#include "base_thread.h"
#include <assert.h>

namespace JoyServer
{

// class CJoyThread

//##ModelId=44CEFAD100D1
CJoyThread::CJoyThread()
{
    m_hThread   = NULL;
    m_threadId  = NULL;
}

//##ModelId=44CEFAD100D2
CJoyThread::~CJoyThread()
{
	assert(m_hThread == NULL);
}

//##ModelId=44CEFAD100CC
DWORD WINAPI CJoyThread::sThreadProc(void* p)
{
    CJoyThread* t = (CJoyThread*)p;
    return t->ThreadProc();
}

//##ModelId=44CEFAD100CF
DWORD CJoyThread::ThreadProc()
{
    return 0;
}

//##ModelId=44CEFAD100D4
bool CJoyThread::Create(bool bSuspend)
{
    assert(m_hThread == NULL);

    DWORD dwFlags = bSuspend ? CREATE_SUSPENDED : 0;

    m_hThread = CreateThread(NULL, 0, sThreadProc, this, dwFlags, &m_threadId);
    if(m_hThread == NULL)
    {
        return false;
    }
    return true;
}

//##ModelId=44CEFAD100DB
void CJoyThread::Destroy()
{
    if(m_hThread == NULL)
    {
        return;
    }
    WaitForSingleObject(m_hThread, INFINITE);
    CloseHandle(m_hThread);
    m_hThread   = NULL;
}

// class CJoyAutoCS2

//##ModelId=44CEFAD100EF
CJoyAutoCS2::CJoyAutoCS2(
    CJoyCriticalSection& cs1, CJoyCriticalSection& cs2):
    m_cs1(cs1), m_cs2(cs2)
{
    CJoyCriticalSection* p1 = &cs1;
    CJoyCriticalSection* p2 = &cs2;

    p1->Lock();
    while(!p2->TryLock())
    {
        p1->Unlock();
        CJoyCriticalSection* t = p2;
        p2 = p1;
        p1 = t;
        p1->Lock();
    }
}

//##ModelId=44CEFAD100FA
CJoyAutoCS2::~CJoyAutoCS2()
{
    m_cs2.Unlock();
    m_cs1.Unlock();
}

} // namespace JoyServer
